//
//  M1FeedBackVC.m
//  NewMarryU
//
//  Created by Cedar on 2018/7/19.
//  Copyright © 2018年 Cedar. All rights reserved.
//

#import "M1FeedBackVC.h"
#import "KSPhotoBrowser.h"
#import "M1FeedBackCell.h"
#import <sys/sysctl.h>


@interface M1FeedBackVC ()<UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UITextViewDelegate, UINavigationControllerDelegate, KSPhotoBrowserDelegate>

@property (nonatomic, strong) UIView *m1_bgView;

@property (nonatomic, strong) UILabel *m1_label;

@property (nonatomic, strong) UICollectionView *m1_collectionView;

@property (nonatomic, strong) NSMutableArray *m1_photoArr;

@property (nonatomic, strong) UITextView *m1_textView;

@property (nonatomic, strong) UILabel *m1_placeholder;

@end

@implementation M1FeedBackVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navigationItem.title = @"意见反馈";
    
//    self.view.backgroundColor = m1_color(0xFFFFFF);
    
    self.m1_tableView.backgroundColor = m1_color(0xF6F8FB);
    
    self.m1_photoArr = [NSMutableArray arrayWithCapacity:0];

    
    [self createRightBarButtonItem:@"提交" titleColor:m1_color(0x333333) action:@selector(commitAction)];
    
    [self createUI];
    
}

- (void)commitAction{
    NSString *text = [self.m1_textView.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    if ([text length] <= 0) {
        [M1Alert m1_alertWithTitle:nil message:@"请输入您要反馈的内容"];
        return;
    }
    
    [self m1_requestPhotos:self.m1_photoArr];
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.item == self.m1_photoArr.count) {
        [self.view endEditing:YES];
        if (self.m1_photoArr.count == 6) {
            [M1Alert m1_alertWithTitle:nil message:@"最多选择6张照片"];
            return;
        }
        M1SheetView *m1_sheet = [[M1SheetView alloc]initWithTitles:@[@"拍照",@"从相册选择"]];
        [m1_sheet m1_show];
        __weak typeof(self) weakSelf = self;
        m1_sheet.click = ^(NSInteger index) {
            [[M1ImagePick manager] m1_pickImages:^(NSArray *photos) {
                [weakSelf.m1_photoArr addObjectsFromArray:photos];
                if (weakSelf.m1_photoArr.count > 0) {
                    weakSelf.m1_label.hidden = YES;
                }
                
                if (SCREENWIDTH < 375) {
                    if (weakSelf.m1_photoArr.count >= 3 && weakSelf.m1_photoArr.count <= 5) {
                        weakSelf.m1_collectionView.frame = CGRectMake(0, weakSelf.m1_collectionView.frame.origin.y, SCREENWIDTH, 170);
                    }else if (weakSelf.m1_photoArr.count >= 6){
                        weakSelf.m1_collectionView.frame = CGRectMake(0, weakSelf.m1_collectionView.frame.origin.y, SCREENWIDTH, 260);
                    }
                }else{
                    if (weakSelf.m1_photoArr.count >= 4 && weakSelf.m1_photoArr.count <= 7) {
                        weakSelf.m1_collectionView.frame = CGRectMake(0, weakSelf.m1_collectionView.frame.origin.y, SCREENWIDTH, 170);
                    }else if (weakSelf.m1_photoArr.count >= 8){
                        weakSelf.m1_collectionView.frame = CGRectMake(0, weakSelf.m1_collectionView.frame.origin.y, SCREENWIDTH, 260);
                    }
                }
                
                [weakSelf.m1_collectionView reloadData];
                
            } type:index maxCount:6-weakSelf.m1_photoArr.count vc:self];
        };
    }else{
        NSMutableArray *items = @[].mutableCopy;
        for (int i = 0; i < _m1_photoArr.count; i++) {
            M1FeedbackCell *cell = (M1FeedbackCell *)[collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
            KSPhotoItem *item = [KSPhotoItem itemWithSourceView:cell.m1_photoImage image:_m1_photoArr[i]];
            [items addObject:item];
        }
        KSPhotoBrowser *browser = [KSPhotoBrowser browserWithPhotoItems:items selectedIndex:indexPath.item];
        browser.delegate = self;
        browser.dismissalStyle = KSPhotoBrowserInteractiveDismissalStyleRotation;
        browser.backgroundStyle = KSPhotoBrowserBackgroundStyleBlur;
        browser.loadingStyle = KSPhotoBrowserImageLoadingStyleIndeterminate;
        browser.pageindicatorStyle = KSPhotoBrowserPageIndicatorStyleDel;
        browser.bounces = YES;
        [browser showFromViewController:self];
    }
}

- (void)ks_photoBrowser:(KSPhotoBrowser *)browser didSelectItem:(KSPhotoItem *)item atIndex:(NSUInteger)index {
    NSLog(@"selected index: %ld", index);
}

- (void)ks_delete_photoBrowser:(KSPhotoBrowser *)browser didSelectItem:(KSPhotoItem *)item atIndex:(NSUInteger)index{
    NSLog(@"删除: %ld", index);
    [self.m1_photoArr removeObjectAtIndex:index];
    
    if (SCREENWIDTH < 375) {
        if (self.m1_photoArr.count >= 3 && self.m1_photoArr.count <= 5) {
            self.m1_collectionView.frame = CGRectMake(0, self.m1_collectionView.frame.origin.y, SCREENWIDTH, 170);
        }else if (self.m1_photoArr.count < 3){
            self.m1_collectionView.frame = CGRectMake(0, self.m1_collectionView.frame.origin.y, SCREENWIDTH, 80);
        }
    }else{
        if (self.m1_photoArr.count >= 4 && self.m1_photoArr.count <= 7) {
            self.m1_collectionView.frame = CGRectMake(0, self.m1_collectionView.frame.origin.y, SCREENWIDTH, 170);
        }else if (self.m1_photoArr.count < 4){
            self.m1_collectionView.frame = CGRectMake(0, self.m1_collectionView.frame.origin.y, SCREENWIDTH, 80);
        }
    }
    
    [self.m1_collectionView reloadData];
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

- (void)ks_cover_photoBrowser:(KSPhotoBrowser *)browser didSelectItem:(KSPhotoItem *)item atIndex:(NSUInteger)index{
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    NSInteger numberOfItem = 0;
    if (self.m1_photoArr.count >= 6) {
        numberOfItem = 6;
    }else{
        numberOfItem = self.m1_photoArr.count + 1;
    }
    return numberOfItem;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    M1FeedbackCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:m1_tableViewCellIdentifier forIndexPath:indexPath];
    
    if (indexPath.item == self.m1_photoArr.count && self.m1_photoArr.count != 9) {
        cell.m1_photoImage.image = [UIImage imageNamed:@"home_icon_addPhoto"];
    }else{
        cell.m1_photoImage.image = self.m1_photoArr[indexPath.item];
    }
    
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(80, 80);
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(0, 15, 0, 15);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 10;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    CGFloat spacing = 0.0;
    if (SCREENWIDTH < 375) {
        spacing = (SCREENWIDTH - 30 - 240) / 2;
    }else{
        spacing = (SCREENWIDTH - 30 - 320) / 3;
    }
    return spacing;
}

- (void)textViewDidChange:(UITextView *)textView{
    if ([textView.text length] > 0) {
        self.m1_placeholder.hidden = YES;
    }else{
        self.m1_placeholder.hidden = NO;
    }
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if ([text isEqualToString:@"\n"]){
        [textView resignFirstResponder];
        return NO;
    }
    return YES;
}

- (void)m1_requestPhotos:(NSArray *)photoArr{
    __weak typeof(self) weakSelf = self;

    if (self.m1_photoArr.count) {
        [[M1FileUpload manager] m1_uploadImages:photoArr progress:^(CGFloat progress) {

        } completion:^(NSArray<NSString *> * _Nullable urls, NSArray<NSDictionary *> * _Nullable pictures, NSError * _Nullable error) {
            NSDictionary *dic = @{@"pic":[pictures mj_JSONString],
                                  @"content":self.m1_textView.text
                                  };
            [M1HttpNet requestWithMethod:m1_feedback_url params:dic success:^(NSDictionary *resDic, NSInteger code, NSString *message) {
                [M1Alert m1_alertWithTitle:nil message:@"提交成功" buttonTitles:@[@"确定"] action:^(NSInteger index) {
                    [weakSelf m1_back];
                }];

            } fail:^(id resDic, NSInteger code, NSString *message) {
                [M1Alert m1_alertWithTitle:nil message:message];
            } showAni:YES];
            
        }];
    } else {
        NSDictionary *dic = @{
                              @"content":self.m1_textView.text
                              };
        [M1HttpNet requestWithMethod:m1_feedback_url params:dic success:^(NSDictionary *resDic, NSInteger code, NSString *message) {
            [M1Alert m1_alertWithTitle:nil message:@"提交成功" buttonTitles:@[@"确定"] action:^(NSInteger index) {
                [weakSelf m1_back];
            }];
        } fail:^(id resDic, NSInteger code, NSString *message) {
            [M1Alert m1_alertWithTitle:nil message:message];
        } showAni:YES];
    }
}

- (void)createUI{
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    self.m1_collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, m1_NAV_HEIGHT + 15, SCREENWIDTH, 80) collectionViewLayout:layout];
    self.m1_collectionView.backgroundColor = [UIColor clearColor];
    self.m1_collectionView.delegate = self;
    self.m1_collectionView.dataSource = self;
    self.m1_collectionView.scrollEnabled = NO;
    [self.m1_collectionView registerNib:[UINib nibWithNibName:@"M1FeedBackCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:m1_tableViewCellIdentifier];
    [self.view addSubview:self.m1_collectionView];
    
    self.m1_label = [[UILabel alloc] init];
    _m1_label.text = @"上传相关截图";
    _m1_label.textColor = m1_color(0x666666);
    _m1_label.font = m1_font(15);
    [self.view addSubview:_m1_label];
    
    [_m1_label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(110);
        make.centerY.equalTo(self.m1_collectionView.mas_centerY);
    }];
    
    self.m1_bgView = [[UIView alloc] init];
    _m1_bgView.backgroundColor = m1_color(0xFFFFFF);
    [self.view addSubview:_m1_bgView];
    [_m1_bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.m1_collectionView.mas_bottom).with.mas_equalTo(20);
        make.left.right.mas_equalTo(0);
        make.height.mas_equalTo(170);
    }];
    
    UIView *line1 = [[UIView alloc] init];
    line1.backgroundColor = m1_color(0xEDEDED);
    [_m1_bgView addSubview:line1];
    
    [line1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.left.right.mas_equalTo(0);
        make.height.mas_equalTo(0.5);
    }];
    
    UIView *line2 = [[UIView alloc] init];
    line2.backgroundColor = m1_color(0xEDEDED);
    [_m1_bgView addSubview:line2];
    
    [line2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(-0.5);
        make.left.right.mas_equalTo(0);
        make.height.mas_equalTo(0.5);
    }];
    
    self.m1_textView = [[UITextView alloc] init];
    _m1_textView.textColor = m1_color(0x333333);
    _m1_textView.font = m1_font(15);
    _m1_textView.delegate = self;
    _m1_textView.returnKeyType = UIReturnKeyDone;
    [_m1_bgView addSubview:_m1_textView];
    
    [_m1_textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(15, 20, 15, 20));
    }];
    
    self.m1_placeholder = [[UILabel alloc] init];
    _m1_placeholder.text = @"请尽可能详细描述您的建议或者您使用软件时遇到的问题、现象等信息";
    _m1_placeholder.textColor = m1_color(0x999999);
    _m1_placeholder.font = m1_font(15);
    _m1_placeholder.numberOfLines = 0;
    [_m1_bgView addSubview:_m1_placeholder];
    
    [_m1_placeholder mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(22);
        make.left.mas_equalTo(23);
        make.right.mas_equalTo(-23);
    }];
    
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

- (void) createRightBarButtonItem:(NSString *)title titleColor:(UIColor *)color action:(SEL)action{
    CGFloat width;
    if ([title length] > 2) {
        width = 70;
    }else{
        width = 40;
    }
    UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(0, 0, width, 44);
    [button setTitle:title forState:UIControlStateNormal];
    [button setTitleColor:color forState:UIControlStateNormal];
    button.titleLabel.font = m1_font(16);
    [button addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * rightBtn = [[UIBarButtonItem alloc] initWithCustomView:button];
    self.navigationItem.rightBarButtonItem = rightBtn;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
